#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#include "thread_parsexml.h"
#include "thread_serial.h"
#include "thread_433m.h"
#include "thread_gsm.h"
#include "thread_camera.h"
#include "thread_upgrade.h"
#include "thread_msgmanage.h"
#include "thread_comm.h"
#include "thread_self_check.h"
#include "thread_alarm.h"
#ifdef MEMWATCH
#include "memwatch.h"
#endif

#define THREAD_NUM  9

void *(*thread[THREAD_NUM])(void *) = {
    thread_parsexml,
    thread_serial,
    thread_433m,
    thread_gsm,
    thread_camera,
    thread_upgrade,
    thread_self_check,
    thread_alarm,
    thread_msgmanage
};

int main( void )
{
    int ret,i;
    int *tret;
    int msgqueueid;
    key_t key;
    pthread_t ntid[THREAD_NUM];
    
#if MEMWATCH
    mwInit();
    mwDoFlush(1);
#endif

    ret = read_cfg(CFG_PATH, 1);
    if ( ret != EN_ERROR_CODE_SUCCESS )
    {
        printf("parse xml failed exit\n");
        return -1;
    }
    //ret = write_cfg("/mnt/mtd/abc.xml");
    
    key = ftok("./", 1);
    if ( key < 0 )
    {
        perror("ftok");
        return -1;
    }
    msgqueueid = msgget(key, IPC_CREAT|0666);
    if ( msgqueueid < 0 )
    {
        perror("msgget");
        return -1;
    }

    
    for (i=0; i < THREAD_NUM; i++)
    {
        ret = pthread_create( &ntid[i], NULL, ( void * )thread[i], (void*)&msgqueueid);
        if ( ret != 0 )
        {
            printf( "Create pthread error!\n" );
            exit( 1 );
        }
    }

    for (i = 0; i < THREAD_NUM; i++)
    {
        ret = pthread_join( ntid[i], ( void ** )( &tret ) );
        if ( ret != 0 )
        {
            printf( "join pthread error! %s\n", strerror( ret ) );
            exit( 1 );
        }
    }
#if MEMWATCH
    mwTerm(); 
#endif
    return ( 0 );
}

